package next.fire.spinus.logx.utils.codec;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.annotation.adapters.HexBinaryAdapter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author hx
 * @date 2019/3/18
 */
public class HmacSHA256 {

    private static final String DEF_CHARSET = "UTF-8";

    public static String genHmacSHA256(String data, String key, String charset) {
        String result = null;
        try {
            SecretKey secretKey = new SecretKeySpec(key.getBytes(isBlank(charset) ? DEF_CHARSET : charset), "HmacSHA256");
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            byte[] bytes = mac.doFinal(data.getBytes(isBlank(charset) ? DEF_CHARSET : charset));
            result = new HexBinaryAdapter().marshal(bytes);
        } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
            System.err.println(e.getMessage());
        }
        return result;
    }

    public static byte[] hmac(byte[] key, String data) {
        try {
            Mac hmac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "HmacSHA256");
            hmac.init(secretKeySpec);
            return hmac.doFinal(data.getBytes(StandardCharsets.UTF_8));
        } catch (InvalidKeyException | NoSuchAlgorithmException var4) {
            throw new RuntimeException("Unable to calculate a request signature: " + var4.getMessage(), var4);
        }
    }

    public static boolean isBlank(String s) {
        return s == null || s.trim().length() == 0;
    }

    public static byte[] sha256(String text) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(text.getBytes(StandardCharsets.UTF_8));
            return md.digest();
        } catch (NoSuchAlgorithmException var2) {
            throw new RuntimeException("Unable to compute hash while signing request", var2);
        }
    }

    public static byte[] sha256(byte[] input) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(input);
            return md.digest();
        } catch (NoSuchAlgorithmException var2) {
            throw new RuntimeException("Unable to compute hash while signing request", var2);
        }
    }
}
